import { getUserInfo, login } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {},
  routes: [...constantRoutes]
}
const mutations = {
  updateToken(state, token) {
    state.token = token
    setToken(token)
  },
  delToken(state) {
    state.token = null
    removeToken()
  },
  updateUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, routes) {
    state.routes = [...constantRoutes, ...routes]
  }
}
const actions = {
  async login(context, data) {
    const res = await login(data)
    context.commit('updateToken', res)
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    context.commit('updateUserInfo', res)
    return res
  },
  logout({ commit }) {
    commit('delToken')
    commit('updateUserInfo', {})
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
